package shangguigu_juc.lock;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.ReentrantLock;

@Data
@NoArgsConstructor
@AllArgsConstructor
class Ticket_1 {

    private int ticketNum;
    private int saleNum;
    private final ReentrantLock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (ticketNum > 0) {
                System.out.println(Thread.currentThread().getName() + ": 卖出第" + (++saleNum)+"张" + " 剩余：" + --ticketNum+"张");
            }
        } finally {
            lock.unlock();
        }
    }
}

public class LSaleTicket {

    public static void main(String[] args) {
        Ticket_1 ticket1 = new Ticket_1(30, 0);
        new Thread(() -> {
            for(int i=0;i<40;i++){
                ticket1.sale();
            }
        }, "t1").start();

        new Thread(() -> {
            for(int i=0;i<40;i++){
                ticket1.sale();
            }
        }, "t2").start();

        new Thread(() -> {
            for(int i=0;i<40;i++){
                ticket1.sale();
            }
        }, "t3").start();
    }
}
